package com.fone.player.online.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.HeaderViewListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.fone.player.R;
import com.fone.player.activity.BaseActivity;
import com.fone.player.activity.main.SplashActivity;
import com.fone.player.client.Callback;
import com.fone.player.client.Configure;
import com.fone.player.client.Error;
import com.fone.player.client.Request;
import com.fone.player.client.SpecllistRst;
import com.fone.player.client.SpecllistRst.Cnt;
import com.fone.player.entity.RedirectInfo;
import com.fone.player.entity.SubjectInfo;
import com.fone.player.online.adapter.SubjectAdapter;
import com.fone.player.sns.ISNSShareManager.ShareStateListener;
import com.fone.player.sns.bean.SNSUserInfo;
import com.fone.player.sns.bean.ShareInfo;
import com.fone.player.sns.impl.SNSShareManager;
import com.fone.player.util.Activity2poster;
import com.fone.player.util.ActivityQueue;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.L;
import com.fone.player.util.ScreenUtil;
import com.fone.player.view.SelectSharePopwindow;
import com.fone.player.widget.xlistview.XListView;
import com.fone.player.widget.xlistview.XListView.IXListViewListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

public class SubjectActivity extends BaseActivity implements IXListViewListener {
	/** 日志标签 */
	private static final String TAG = "SubjectActivity";

	private View titleView;
	private View headerView;
	private ImageView posterPic;
	private ImageView moreTag;
//	private TextView posterName;
	private TextView memo;
	private TextView guide;
	
	private Button mLeftBt;
	private Button mRightBt;
	private TextView mTitleTv;
	
	private XListView mListView;

	private SubjectAdapter adapter;
	DisplayImageOptions options;
	
	private int lineCount = 1;
	
	private String url;
	private String shost;
	private String host;
	private String clid;
	
	private String weibourl;
	private String nurl;
	private String name;
	private String picurl;
	
	private boolean isTextShow = false;
	private boolean isFromNotication = false;
	
//	private ArrayList<Cnt> cntList = new ArrayList<Cnt>();
	private List<SubjectInfo> subjectList = new ArrayList<SubjectInfo>();

	private static final int SUCCESS = 0;
//	private static final int FAILURE = 1;
	
	private SelectSharePopwindow mSelectSharePopwindow;
	private MyShareStateListener mShareStateListener;
	
	private boolean isFirst = true;
	
	private final int UPDATESERVER = 1;
	private final int SHOWMORETEXT = 10;
	
	
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			
			case UPDATESERVER:
				isFirst = true;
//				initColumnData(url);
				onRefresh();
				break;
				
			case SHOWMORETEXT:
				//考虑用控件的高度判断当前是否展开
				L.v(TAG, "textview", "-- end --");
				if (lineCount <=1) {
					return;
				}
				
				if(!isTextShow ){
					moreTag.setBackgroundResource(R.drawable.home_title_arrows);
					memo.setLines(lineCount);
					isTextShow = true;
				}else{
					moreTag.setBackgroundResource(R.drawable.home_title_arrows_click);
					memo.setLines(1);
					isTextShow = false;
				}
				break;

			default:
				break;
			}
		}
	};


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_subject);
		
		getIntentData();
		
		initView();
		
		mHandler.sendEmptyMessage(UPDATESERVER);
//		initSubjectData(url);
	}
	
	/**
	 * 获得Intent传递值
	 */
	private void getIntentData(){
		Intent intent = getIntent();
		url = intent.getStringExtra("url");
		weibourl = intent.getStringExtra("weibo");
		isFromNotication = intent.getBooleanExtra("notice", false);
	}
	
	/**
	 * 布局控件初始化
	 */
	private void initView() {
		
		options = new DisplayImageOptions.Builder()
		.showImageOnLoading(R.drawable.default_720_340)
		.showImageForEmptyUri(R.drawable.default_720_340)
		.showImageOnFail(R.drawable.default_720_340)
		.cacheInMemory(true)
		.cacheOnDisk(true)
		.considerExifParams(true)
		.build();
		
		titleView = (View)findViewById(R.subject.common_title);
		
		mLeftBt = (Button) findViewById(R.id.common_title_left_bt);
		mRightBt = (Button) findViewById(R.id.common_title_right_bt);
		mTitleTv = (TextView) findViewById(R.id.common_left_title_tv);
		
		mListView = (XListView) findViewById(R.subject.list);
		
		headerView = LayoutInflater.from(this).inflate(R.layout.view_subject_header, null, false);
		posterPic = (ImageView) headerView.findViewById(R.subject.pic);
		moreTag = (ImageView) headerView.findViewById(R.subject.more_tag);
		moreTag.setVisibility(View.INVISIBLE);
		memo = (TextView) headerView.findViewById(R.subject.memo);
		guide = (TextView) headerView.findViewById(R.subject.guide);
		
		//测试
//		String str = "\t\t\t\t\t\t\t\t\t\t"+"你的遗体将慢慢消散，化为永恒，就像沙漠中的沙砾那样";
//		memo.setText(str);
		
		memo.setOnClickListener(new TextClicker());
		mLeftBt.setOnClickListener(new BtnOnClicker());
		mRightBt.setOnClickListener(new BtnOnClicker());
		
		if(TextUtils.isEmpty(weibourl)){
			mRightBt.setVisibility(View.INVISIBLE);
		}else{
			mRightBt.setVisibility(View.VISIBLE);
			mRightBt.setText("分享");
		}
		
		mTitleTv.setVisibility(View.VISIBLE);
		
		mListView.setPullLoadEnable(false);
		mListView.setPullRefreshEnable(true);
		mListView.setEnableDragLoadMore(false);
		mListView.setXListViewListener(this);
//		mListView.setOnScrollListener(this);
		
//		mListView.addHeaderView(headerView);
		mListView.addHeaderView(headerView, null, false);
		
		adapter = new SubjectAdapter(SubjectActivity.this, shost, subjectList);
		mListView.setAdapter(adapter);
		mListView.setOnItemClickListener(new SubjectItemClicker());
		
	}

	private boolean initSubjectData(String path) {
		// 如果没有网络，则不向服务器申请数据
		if (FoneUtil.isNetOkWithToast(SubjectActivity.this) && !TextUtils.isEmpty(url) && url.length() > 14) {
			Request.getInstance().specllist(FoneUtil.onlineUrl(path), new SubjectCallBack());
			L.v(TAG, "initColumnData", FoneUtil.onlineUrl(path));
			return true;
		} else {
			return false;
		}
	}


	private class SubjectCallBack implements Callback<SpecllistRst> {

		@Override
		public void onSuccess(SpecllistRst t) {
			mListView.stopRefresh();
			mListView.stopLoadMore();
			
			updateSubject(t);
		}

		@Override
		public void onFailure(Error error) {
			mListView.stopRefresh();
			mListView.stopLoadMore();
			L.v(TAG, "SubjectCallBack", "-onFailure-" + error.toString());
		}

	}
	
	private void updateSubject(SpecllistRst t){
		L.v(TAG, "HorizontalCallBack", "-onSuccess-" + t.result);
		
		headerView.setVisibility(View.VISIBLE);
		
		if (t.result == SUCCESS) {
			
			if(isFirst){
				subjectList.clear();
				adapter.notifyDataSetChanged();
				getServerData(t);
				guide.setVisibility(View.VISIBLE);
				
//				String str = "\u3000\u3000\u3000\u3000"+"小说里面写丹妮怀疑自己是真龙,而最后烧了自己后证明自己是真龙。但是一般人的思路不应该在烧自己之前先拿根蜡烛试试吗？要是丹妮早点验证自己不焚，";
//				memo.setText(str);
				if(!TextUtils.isEmpty(t.memo)){
					memo.setText("\u3000\u3000\u3000\u3000"+t.memo.replace("\t", "").trim());
					if (memo.getLineCount() > 1) 
						moreTag.setVisibility(View.VISIBLE);
				}
				if(t.pic!=null){
					ImageLoader.getInstance().displayImage(FoneUtil.getAbsoluteUrl("", shost, t.pic), posterPic, options);
				}
			}
			
			frashColumnListView(t);
			loadNextPage(t);
			isFirst = false;
			
		} else {

			// 数据返回不正确 不允许上拉加载更多,允许下拉刷新
			mListView.setPullRefreshEnable(false);
			mListView.setEnableDragLoadMore(false);
			mListView.setPullRefreshEnable(true);
		}
	}
	
	/**
	 * 初始化服务器返回参数
	 */
	private void getServerData(SpecllistRst t) {
		// TODO Auto-generated method stub
		if(t.shost != null){
			shost = t.shost;
			L.v(TAG, "initServerInfo", "-shost-" + shost);
		}
		
		if(t.host != null){
			host = t.host;
			L.v(TAG, "initServerInfo", "-host-" + host);
		}
		
		if(t.label != null && t.label.clid != null){
			clid = t.label.clid;
			L.v(TAG, "initServerInfo", "-clid-" + clid);
		}
		
		if(t.desc != null){
			mTitleTv.setText(t.desc);
			L.v(TAG, "initServerInfo", "-desc-" + t.desc);
		}
		
	}
	
	/**
	 * 刷新"列表"数据
	 */
	private void frashColumnListView(SpecllistRst t) {
		// TODO Auto-generated method stub
		if(t.cnts != null && t.cnts.cntList != null && !t.cnts.cntList.isEmpty()){
			
			for (Cnt cnt : t.cnts.cntList) {
				SubjectInfo info = new SubjectInfo();
				info.name = cnt.name;
				info.utp = cnt.utp;
				info.url = cnt.url;
				info.dfnt = cnt.dfnt;
				info.vgurl = cnt.url;
				info.xyzplayurl = cnt.url;
				info.btnply = cnt.btnply;
				info.weibourl = cnt.weibourl;
				info.pic1 = cnt.pic1;
				info.pic2 = cnt.pic2;
				info.ourl = cnt.ourl;
				info.quality = cnt.quality;
				info.updatedetail = cnt.updatedetail;
				info.desc = cnt.desc;
				
				subjectList.add(info);
			}
			
			adapter.initData(shost, subjectList);
			adapter.notifyDataSetChanged();
		}
	}
	
	/** "栏目"是否存在下一页 . */
	private void loadNextPage(SpecllistRst t) {
		// TODO Auto-generated method stub
		if(t.rp != null && t.rp.m == 1 && t.rp.nurl != null){
			nurl = t.rp.nurl;
			mListView.setEnableDragLoadMore(true);
			mListView.setPullLoadEnable(true);
		}else {
			// 隐藏上拉更多
			mListView.setEnableDragLoadMore(false);
			mListView.setPullLoadEnable(false);
		}
	}
	
	private void getTextLine(){
		memo.post(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				lineCount = memo.getLineCount();
				Message message = mHandler.obtainMessage();
				message.what = SHOWMORETEXT;
				mHandler.sendMessage(message);
				
				L.v(TAG, "onCreate", "---TextView Line---" + memo.getLineCount());
			}
		});
	}

	
	private class TextClicker implements OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			L.v(TAG, "TextClicker", "---TextView Line---" + memo.getLineCount());
			
			if(TextUtils.isEmpty(memo.getText().toString())){
				return;
			}else{
				L.v(TAG, "textview", "-- star --");
				getTextLine();
			}
		}
		
	}

	private class SubjectItemClicker implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			// 判断网络状态
			if (FoneUtil.isNetOk(SubjectActivity.this)) {
				HeaderViewListAdapter hdAdapter = (HeaderViewListAdapter)mListView.getAdapter();
				SubjectInfo info = (SubjectInfo)hdAdapter.getWrappedAdapter().getItem((int)id);
//				SubjectInfo info = (SubjectInfo)adapter.getItem(arg2-1);
				
				if(info==null){
					return;
				}
				L.v(TAG, "CommonItemClicker", info.name);
				Activity2poster.startActivity(SubjectActivity.this, getRedirectInfo(info));
			}
		}
	}
	
	private RedirectInfo getRedirectInfo(SubjectInfo info){
		RedirectInfo redirectInfo = new RedirectInfo();
		redirectInfo.host = host;
		redirectInfo.utp = info.utp;
		redirectInfo.weibourl = info.weibourl;
		redirectInfo.url = info.url;
		redirectInfo.vgurl = info.url;
		redirectInfo.xyzplayurl = info.url;
		redirectInfo.dnfs = info.dfnt;
		redirectInfo.name = info.name;
		redirectInfo.ourl = info.ourl;
		redirectInfo.btnply = info.btnply;
		redirectInfo.pic = info.pic2;
		return redirectInfo;
	}

	@Override
	public void onRefresh() {
		// TODO 下拉刷新
		mListView.onLoad();
		//如果"栏目"下拉刷新
		if(initSubjectData(url)){
			isFirst = true;
		}else{
			mListView.stopRefresh();
			mListView.stopLoadMore();
		}
		
	}

	@Override
	public void onLoadMore() {
		// TODO 上拉更多
		if(initSubjectData(nurl)){
			isFirst = false;
		}else{
			mListView.setEnableDragLoadMore(true);
			mListView.setPullLoadEnable(true);
		}
	}

	private class BtnOnClicker implements OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.common_title_left_bt:
				finish();
				break;
				
			case R.id.common_title_right_bt:
//				showShortToast("分享按钮相应点击");
				showSharePopWindow();
				break;

			default:
				break;
			}
		}
		
	}
	
	
	// 展示分享的popwindow
	private void showSharePopWindow() {
		ShareInfo info = new ShareInfo(SNSShareManager.TENCENT_WEIXIN_FRIEND_TYPE);
		String share_word_prefix = getResources().getString(R.string.select_share_word_prefix);
		String share_link_address = getResources().getString(R.string.select_share_link_address);
		info.title = name;
		info.titleUrl = share_link_address;
		info.text = share_word_prefix + name;
		info.videoUrl = FoneUtil.getAbsoluteUrl(Configure.getEndPoint(), null, weibourl);
		info.imageUrl = picurl;
		info.site = "100tv";
		info.siteUrl = share_link_address;

		if (mShareStateListener == null) {
			mShareStateListener = new MyShareStateListener();
		}
		if (mSelectSharePopwindow == null) {
			Rect frame = new Rect();
			this.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); // mActivity指当前的activity
			int Height = ScreenUtil.getScreenHeightPix(this) - titleView.getHeight() - frame.top;
			mSelectSharePopwindow = new SelectSharePopwindow(this, Height, ScreenUtil.getScreenWidthPix(this), mShareStateListener);
		}

		mSelectSharePopwindow.show(titleView, info);

	}
	
	// 分享的监听器
	private class MyShareStateListener implements ShareStateListener {

		@Override
		public void shareAction(int action, String info) {
			switch (action) {
			case ShareStateListener.SHARING:
				L.v(TAG, "shareAction", "SHARING");
				break;
			case ShareStateListener.SHARE_SUCCESS:
				L.v(TAG, "shareAction", "SHARE_SUCCESS");
				break;
			case ShareStateListener.SHARE_FAILED:
				L.v(TAG, "shareAction", "SHARE_FAILED");
				break;
			case ShareStateListener.SHARE_CANCEL:
				L.v(TAG, "shareAction", "SHARE_CANCEL");
				break;
			default:
				break;
			}

		}

		@Override
		public void onUserInfoComplete(SNSUserInfo user) {

		}

	}
	
	
	@Override
	public void finish() {
		// 未启动应用的通知过来  要打开应用
		if (isFromNotication && ActivityQueue.getSize() <= 1) {
			Intent i = new Intent(SubjectActivity.this, SplashActivity.class);
			startActivity(i);
		}
		super.finish();
	}
}
